import os
import sys
from gtk import *
from pango import ELLIPSIZE_MIDDLE
from xmmsclient import *
from os.path import basename
from urllib2 import url2pathname
from core import *


class Medialib(VBox, MedialibCore):
    def __init__(self, xmms2):
        VBox.__init__(self)
        MedialibCore.__init__(self, xmms2)
        treeview = TreeView(self.medialib)
        treeview.set_headers_visible(True)
        selection = treeview.get_selection()
        selection.set_mode(SELECTION_MULTIPLE)
        
        for k, i in [("Id", 0), ("Title", 1), ("Album", 2), 
            ("Artist", 3), ("Times played", 4)]:
            cell = CellRendererText()
            cell.set_property("ellipsize", ELLIPSIZE_MIDDLE)
            col = TreeViewColumn(k, cell, text=i)
            col.set_reorderable(True)
            col.set_resizable(True)
            col.set_expand(True)
            col.set_visible(True)
            treeview.append_column(col)
        
        scroll = ScrolledWindow()
        scroll.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
        scroll.add(treeview)
        self.pack_start(scroll)
        hbox = HBox()
        label = Label("Filter: ")
        line_entry = Entry()
        hbox.pack_start(label, expand=False)
        hbox.pack_start(line_entry)
        self.pack_start(hbox, expand=False)
        
        treeview.connect("row-activated", self.on_row_activated)
        line_entry.connect("changed", self.filter)
        
    def on_row_activated(self, treeview, path, column):
        model = self.medialib.get_model()
        id = model[path][MLIB_ID]
        self.xmms2.playlist_add_id(id)
    

if __name__ == "__main__":
    import xmmsclient.glib
    
    xmms2 = XMMS("mlibtest")
    try:
        xmms2.connect(os.getenv("XMMS_PATH"))
    except:
        print "Could not connect to xmms2d. Aborting"
        exit(1)
    xmmsclient.glib.GLibConnector(xmms2)
    mlib = Medialib(xmms2)
    w = Window()
    w.add(mlib)
    w.show_all()
    w.connect("delete-event", lambda w, e: main_quit())
    mlib.load_medialib()
    main()
